import pymapgis
import os
import glob
import geopandas as gpd
from shapely.geometry import Polygon, Point, LineString, MultiPolygon, MultiLineString

# 输入文件夹路径
input_path = r"G:\2025工作\东阳十四五规划\附图4东阳市地质灾害重点工程图"
# 输出文件夹路径和GDB名称
output_path = r'G:\2025工作\东阳十四五规划'
output_gdb = os.path.join(output_path, "combined_data.gdb")

# 目标文件扩展名
target_suffix = [".wl", ".wt", ".wp"]

# 确保输出文件夹存在
os.makedirs(output_path, exist_ok=True)

# 遍历每种文件类型
for suffix in target_suffix:
    # 查找所有匹配的文件
    files = glob.glob(os.path.join(input_path, f"*{suffix}"))
    for file in files:
        try:
            # 读取MapGIS文件
            with pymapgis.Reader(file) as f:
                attributes = f.data  # 属性表数据
                geometries = f.geom   # 几何对象
            
            # 创建GeoDataFrame
            gdf = gpd.GeoDataFrame(attributes, geometry=geometries)
            
            # 设置坐标系（根据实际数据调整EPSG）
            gdf.crs = "EPSG:2386"
            
            # 检查几何类型，进行处理
            print(f"Geometry types found: {gdf.geom_type.unique()}")
            
            # 分离几何类型，并将 Polygon 转换为 MultiPolygon
            points_gdf = gdf[gdf.geom_type == 'Point']
            polygons_gdf = gdf[gdf.geom_type.isin(['Polygon', 'MultiPolygon'])].copy()
            polygons_gdf['geometry'] = polygons_gdf['geometry'].apply(lambda geom: MultiPolygon([geom]) if isinstance(geom, Polygon) else geom)
            lines_gdf = gdf[gdf.geom_type.isin(['LineString', 'MultiLineString', 'CircularString', 'CompoundCurve', 'MultiCurve'])]
            
            # 检查是否存在不支持的几何类型并尝试转换
            unsupported_gdf = gdf[~gdf.geom_type.isin(['Point', 'Polygon', 'MultiPolygon', 'LineString', 'MultiLineString', 'CircularString', 'CompoundCurve', 'MultiCurve'])]
            if not unsupported_gdf.empty:
                print(f"Unsupported geometry types found in file {file}: {unsupported_gdf.geom_type.unique()}")
                # 尝试将不支持的几何类型转换为支持的类型
                unsupported_gdf['geometry'] = unsupported_gdf['geometry'].apply(
                    lambda geom: MultiPolygon([geom]) if isinstance(geom, Polygon) else 
                                LineString(geom) if isinstance(geom, (MultiLineString, LineString)) else 
                                Point(geom) if isinstance(geom, (Point)) else None
                )
                # 过滤掉仍然不支持的几何类型
                unsupported_gdf = unsupported_gdf.dropna(subset=['geometry'])
                
                # 将转换后的几何加入到相应的GeoDataFrame中
                points_gdf = points_gdf.append(unsupported_gdf[unsupported_gdf.geom_type == 'Point'])
                polygons_gdf = polygons_gdf.append(unsupported_gdf[unsupported_gdf.geom_type.isin(['Polygon', 'MultiPolygon'])])
                lines_gdf = lines_gdf.append(unsupported_gdf[unsupported_gdf.geom_type.isin(['LineString', 'MultiLineString'])])
            
            # 检查GDB是否存在以决定写入模式
            gdb_exists = os.path.exists(output_gdb)
            mode = 'a' if gdb_exists else 'w'
            
            # 分别写入不同几何类型的图层
            if not points_gdf.empty:
                points_layer_name = os.path.splitext(os.path.basename(file))[0] + "_points"
                points_gdf.to_file(
                    output_gdb,
                    driver='OpenFileGDB',
                    layer=points_layer_name,  # 使用文件名+_points作为图层名称
                    mode=mode
                )
                print(f"成功写入点图层: {points_layer_name}")
            
            if not polygons_gdf.empty:
                polygons_layer_name = os.path.splitext(os.path.basename(file))[0] + "_polygons"
                polygons_gdf.to_file(
                    output_gdb,
                    driver='OpenFileGDB',
                    layer=polygons_layer_name,  # 使用文件名+_polygons作为图层名称
                    mode=mode
                )
                print(f"成功写入多边形图层: {polygons_layer_name}")
            
            if not lines_gdf.empty:
                lines_layer_name = os.path.splitext(os.path.basename(file))[0] + "_lines"
                lines_gdf.to_file(
                    output_gdb,
                    driver='OpenFileGDB',
                    layer=lines_layer_name,  # 使用文件名+_lines作为图层名称
                    mode=mode
                )
                print(f"成功写入线图层: {lines_layer_name}")

        except Exception as e:
            print(f"处理文件 {file} 时出错: {str(e)}")

print("所有文件处理完成。")
